package com.lei.mq;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 延迟消息实现,、
 * 延迟消息必须通过两个队列实现，通过队列1消息过期后发送给队列2实现延迟消息
 * 官网：http://www.rabbitmq.com/dlx.html
 * Created by Administrator on 2019/2/26.
 */
@Component
public class S05DelayQueueProducer {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //路由key
    private static final String RUOTE_KEY="key";
    private static final String EXCHANGE="expiration.statics.exchange";
    private static final String NEW_EXCHANGE="new.expiration.statics.exchange";
    private static final String NEW_RUOTE_KEY="new.key";
    /**
     * 定义一个exchange交换机
     * @return
     */
    @Bean
    public DirectExchange expirationStatics(){
        return new DirectExchange(EXCHANGE);
    }
    @Bean
    public DirectExchange newExpirationStatics(){
        return new DirectExchange(NEW_EXCHANGE);
    }
    @Bean
    public Queue newQueue(){
        return new Queue("expiration.new.queue");
    }
    /**
     * 定义一个队列
     * @return
     */
    @Bean
    public Queue expirationQueue(){
        Map<String, Object> args = new HashMap<>(8);
        //消息过期死亡后路由给some.exchange.name交换机
        args.put("x-dead-letter-exchange", NEW_EXCHANGE);
        //消息过期死亡后路由key
        args.put("x-dead-letter-routing-key", NEW_RUOTE_KEY);
        return new Queue("expiration.queue",true,false,false,args);
    }

    @Bean
    public Binding bindingExpiration() {
        return BindingBuilder.bind(expirationQueue()).to(expirationStatics()).with(RUOTE_KEY);
    }
    @Bean
    public Binding newBindingExpiration() {
        return BindingBuilder.bind(newQueue()).to(newExpirationStatics()).with(NEW_RUOTE_KEY);
    }
    @Scheduled(fixedDelay = 2000L)
    public void send() {
        System.out.println("S05DelayQueueProducer");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
        String content = "S05DelayQueueProducer "+format.format(new Date());
        this.rabbitTemplate.convertAndSend(EXCHANGE, RUOTE_KEY, content,e->{
            //10秒过期时间设置，过期后自动消费
            e.getMessageProperties().setExpiration(String.valueOf(10000));
            return e;
        });
    }
}
